<?php

class Bs_club {
	public function __construct() {
		add_action( 'admin_enqueue_scripts', array(&$this, 'bs_admin_enqueue_scripts') );
		add_action( 'init', array(&$this, 'create_club_post_type') );
		add_action( 'admin_head', array(&$this, 'remove_seo_filter'), 20 );
		add_filter( 'manage_clubs_posts_columns', array(&$this, 'replace_club_columns'), 100 );
		add_action( 'manage_clubs_posts_custom_column', array(&$this, 'add_club_columns_data') );
		add_filter( 'manage_edit-clubs_sortable_columns', array(&$this, 'sortable_columns') );
		add_action( 'pre_get_posts', array(&$this, 'columns_orderby') );
	}

	/**
	 * Add stylesheets and scripts only for admin
	 */
	public function bs_admin_enqueue_scripts($hook)
	{
	   wp_register_style( 'bs-admin-css', BS_ASSETS_URL . 'css/admin.css', false, '1.0.0' );
	   wp_enqueue_style( 'bs-admin-css' );
	   
	   wp_enqueue_script( 'bs-admin-js', BS_ASSETS_URL. 'js/admin.js', array('jquery'), '1.0.0' );
	}

	public function create_club_post_type() {
		register_post_type('clubs',
			array(
				'labels' => array(
					'name' => __( 'Klubber' ),
					'singular_name' => __( 'Klub' )
				),
				'public' => true,
      			'has_archive' => true,
      			'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
			)
		);
	}

	public function remove_seo_filter() {
	    global $wpseo_metabox;
	    global $post;
	    $post_id = get_post_type($post->id);

	    if($post_id === 'clubs') {

		    if ( $wpseo_metabox ) {
		        remove_action( 'restrict_manage_posts', array( $wpseo_metabox, 'posts_filter_dropdown' ) );
		    }
		}
	}

	public function replace_club_columns($columns) {

		$new_columns = array(
			'nation' => __('Land', 'fodfessor'),
			'city' => __('By', 'fodfessor'),
			'stadium' => __('Stadion', 'fodfessor')
		);
		return array_merge(array_slice($columns, 0, 3), $new_columns);
	}

	public function add_club_columns_data($column) {

		switch ($column) {
			case 'thumbnail':
				$value = get_post_meta(get_the_ID());
				echo $value[$column[0]];
				break;

			case 'nation':
				$value = get_field($column, get_the_ID());
				echo $value;
				break;

			case 'city':
				$value = get_field($column, get_the_ID());
				echo $value;
				break;
			
			case 'stadium':
				$value = get_field($column, get_the_ID());
				echo $value;
				break;
		}
	}

	public function sortable_columns( $columns ) {
	    $columns['nation'] = 'nation';
	    $columns['city'] = 'city';
	    $columns['stadium'] = 'stadium';
	 
	    return $columns;
	}

	public function columns_orderby( $query ) {
	    if( ! is_admin() )
	        return;
	 
	 	$valid_columns = array('nation', 'city', 'stadium');
	    $orderby = $query->get( 'orderby');
	 
	 	if(in_array($orderby, $valid_columns)) {
	 		$query->set('meta_key', $orderby);
	 		$query->set('orderby','meta_value');
	 	}
	}
}

new Bs_club();